package com.guxingke.typecho4j.widget.provider.comment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.guxingke.typecho4j.jfinal.model.Comment;
import com.guxingke.typecho4j.util.ControllerUtil;
import com.guxingke.typecho4j.util.PageBean;
import com.guxingke.typecho4j.widget.WidgetProvider;
import com.guxingke.typecho4j.widget.provider.CommentBaseWidget;
import com.jfinal.core.Controller;

/**
 * 内容评论组件，对应某post,page的评论数据
 * 
 * @author guxingke
 * */
public class CommentsWidget extends CommentBaseWidget implements WidgetProvider {

	private Map<String, List<Comment>> commentsCache = new HashMap<String, List<Comment>>();

	@Override
	public void excute(Controller controller) {
		String slug = ControllerUtil.getUrlPara(controller);

		Long cid;
		try {
			cid = Long.parseLong(slug);
		} catch (NumberFormatException e) {
			cid = null;
		}

		Integer page = controller.getParaToInt("page");
		if (page == null) {
			page = 1;
		}
		List<Comment> comments = null;
		if (cid != null) {
			comments = getCommentsByCidAndPage(cid, page);
		} else {
			comments = getCommentsByCSlugAndPage(slug, page);
		}
		controller.setAttr("comments", comments);
	}

	private List<Comment> getCommentsByCSlugAndPage(String slug,
			Integer page) {
		String key = slug + "-" + page;
		if (commentsCache.containsKey(key)) {
			return commentsCache.get(key);
		}
		List<Comment> comments = null;
		comments = getCommentsByCSlug(slug, new PageBean(page,
				constants.getPageSize()));
		if (!comments.isEmpty()) {
			commentsCache.put(key, comments);
		}
		return comments;
	}

	private List<Comment> getCommentsByCidAndPage(Long cid, Integer page) {
		String key = cid + "-" + page;
		if (commentsCache.containsKey(key)) {
			return commentsCache.get(key);
		}
		List<Comment> comments = null;
		comments = getCommentsByCid(cid,
				new PageBean(page, constants.getPageSize()));
		if (!comments.isEmpty()) {
			commentsCache.put(key, comments);
		}
		return comments;
	}

	@Override
	public void refresh() {
		this.commentsCache.clear();
	}
}
